package wjx.database.bean;

import java.awt.Color;
import java.util.Enumeration;

import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.border.EtchedBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;

//import sun.swing.table.DefaultTableCellHeaderRenderer;

public class JTableUtils {

	static public void setTable(JTable table) {
		// 设置表数据居中显示
		DefaultTableCellRenderer cr = new DefaultTableCellRenderer();
		cr.setHorizontalAlignment(JLabel.CENTER);
		table.setDefaultRenderer(Object.class, cr);
		// 设置网格线
		table.setShowHorizontalLines(true);
		table.setShowVerticalLines(true);
		table.setBorder(new EtchedBorder(EtchedBorder.RAISED));
		table.setGridColor(Color.BLACK);
//		table.setAutoResizeMode(4);
		// 自适应调整列宽
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); 
		JTableHeader header = table.getTableHeader();
		int rowCount = table.getRowCount();

		Enumeration columns = table.getColumnModel().getColumns();
		while (columns.hasMoreElements()) {
			TableColumn column = (TableColumn) columns.nextElement();
			int col = header.getColumnModel().getColumnIndex(column.getIdentifier());
			int width = (int) table.getTableHeader().getDefaultRenderer()
					.getTableCellRendererComponent(table, column.getIdentifier(), false, false, -1, col)
					.getPreferredSize().getWidth();
			for (int row = 0; row < rowCount; row++) {
				int preferedWidth = (int) table.getCellRenderer(row, col)
						.getTableCellRendererComponent(table, table.getValueAt(row, col), false, false, row, col)
						.getPreferredSize().getWidth();
				width = Math.max(width, preferedWidth);
			}
			header.setResizingColumn(column); // 此行很重要
			column.setWidth(width + table.getIntercellSpacing().width);
		}
		table.setRowHeight(25);
		// 设置表头居中显示
//		DefaultTableCellHeaderRenderer thr = new DefaultTableCellHeaderRenderer();
//		thr.setHorizontalAlignment(JLabel.CENTER);
//		table.getTableHeader().setDefaultRenderer(thr);
	}

}
